<template>
  <MainLayout>
    <div class="homeworks-page">
      <!-- 页面头部 -->
      <div class="page-header">
        <div class="header-background"></div>
        <div class="header-content">
        <div class="header-left">
            <div class="header-icon">
              <el-icon size="32"><Collection /></el-icon>
            </div>
            <div class="header-text">
              <h1>{{ authStore.hasAnyRole(['teacher', 'admin']) ? '作业管理' : '我的作业' }}</h1>
              <p>
                {{ authStore.hasAnyRole(['teacher', 'admin']) 
                  ? '管理课程作业，布置题目给学生，监控完成情况' 
                  : '查看和完成老师布置的作业，提升学习效果' 
                }}
          </p>
        </div>
          </div>
          <div class="header-actions">
            <el-button 
              type="primary" 
              size="large" 
              @click="refreshHomeworks" 
              class="action-btn primary-btn"
            >
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button
              v-if="authStore.hasAnyRole(['teacher', 'admin'])"
              type="success"
              size="large"
              @click="showCreateDialog = true"
              class="action-btn success-btn"
            >
              <el-icon><Plus /></el-icon>
              创建作业
            </el-button>
          </div>
        </div>
      </div>

      <!-- 筛选和搜索 -->
      <el-card class="filter-card" shadow="hover">
        <template #header>
          <div class="filter-header">
            <el-icon size="20" class="filter-icon"><Filter /></el-icon>
            <span class="filter-title">作业筛选</span>
            <el-tag type="info" size="small">{{ filteredHomeworks.length }} 个作业</el-tag>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="searchQuery"
              placeholder="搜索作业标题或描述..."
              class="filter-input"
              clearable
              @input="filterHomeworks"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select 
              v-model="statusFilter" 
              placeholder="作业状态" 
              clearable 
              @change="filterHomeworks"
              class="filter-select"
            >
              <el-option label="全部状态" value="" />
              <el-option label="进行中" value="active" />
              <el-option label="已结束" value="ended" />
              <el-option label="未开始" value="pending" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select 
              v-model="courseFilter" 
              placeholder="课程" 
              clearable 
              @change="filterHomeworks"
              class="filter-select"
            >
              <el-option label="全部课程" value="" />
              <el-option
                v-for="course in courses"
                :key="course.id"
                :label="course.name"
                :value="course.id"
              />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" text @click="clearFilters" class="clear-filters-btn">
              <el-icon><Delete /></el-icon>
              清除筛选
            </el-button>
          </el-col>
        </el-row>
      </el-card>

      <!-- 统计信息 -->
      <div class="stats-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon total-icon">
                <el-icon size="24"><Collection /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ filteredHomeworks.length }}</div>
                <div class="stat-label">总作业数</div>
                </div>
                </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon active-icon">
                <el-icon size="24"><Clock /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ activeHomeworksCount }}</div>
                <div class="stat-label">进行中</div>
                </div>
                </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon completed-icon">
                <el-icon size="24"><Check /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ completedHomeworksCount }}</div>
                <div class="stat-label">已完成</div>
                </div>
                </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon score-icon">
                <el-icon size="24"><TrendCharts /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ averageScore }}分</div>
                <div class="stat-label">平均分</div>
                </div>
                </div>
          </el-col>
        </el-row>
      </div>

      <!-- 作业列表 -->
      <el-card class="homeworks-table-card" shadow="hover">
        <template #header>
          <div class="table-header">
            <div class="header-left">
              <el-icon size="20" class="header-icon"><List /></el-icon>
              <span class="header-title">作业列表</span>
              <el-tag type="info" size="small">{{ filteredHomeworks.length }} 个作业</el-tag>
            </div>
            <div class="header-right">
              <el-button type="primary" text @click="refreshHomeworks" class="refresh-btn">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          :data="filteredHomeworks"
          v-loading="loading"
          style="width: 100%"
          class="homeworks-table"
          :header-cell-style="{ background: '#f8f9fa', color: '#606266' }"
          stripe
          :row-class-name="getRowClassName"
        >
          <el-table-column prop="id" label="ID" width="80" align="center">
            <template #default="{ row }">
              <el-tag size="small" type="info">#{{ row.id }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="作业信息" min-width="350">
            <template #default="{ row }">
              <div class="homework-info">
                <div class="homework-header">
                  <div class="homework-icon">
                    <el-icon size="20"><Collection /></el-icon>
                  </div>
                  <div class="homework-details">
                <h4 class="homework-title">{{ row.title }}</h4>
                <p class="homework-description">{{ row.description }}</p>
                  </div>
                </div>
                <div class="homework-meta">
                  <el-tag 
                    :type="getStatusTagType(row.status)" 
                    size="small"
                    class="status-tag"
                  >
                    <el-icon size="12" class="tag-icon">
                      <component :is="getStatusIcon(row.status)" />
                    </el-icon>
                    {{ getStatusText(row.status) }}
                  </el-tag>
                  <span class="problem-count">
                    <el-icon size="14"><Document /></el-icon>
                    {{ row.problems?.length || 0 }} 道题
                  </span>
                  <span class="total-points">
                    <el-icon size="14"><Star /></el-icon>
                    {{ row.total_points }}分
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="course_name" label="课程" width="140">
            <template #default="{ row }">
              <div class="course-cell">
                <div class="course-icon">
                  <el-icon size="16"><Reading /></el-icon>
                </div>
                <span class="course-name">{{ row.course_name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="截止时间" width="180">
            <template #default="{ row }">
              <div class="deadline-info">
                <span v-if="row.deadline" :class="getDeadlineClass(row.deadline)">
                  <el-icon size="16" class="deadline-icon"><Timer /></el-icon>
                  {{ formatDate(row.deadline) }}
                </span>
                <span v-else class="no-deadline">
                  <el-icon size="16"><Timer /></el-icon>
                  无截止时间
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="{ row }">
              <div class="time-cell">
                <el-icon size="16" class="time-icon"><Calendar /></el-icon>
                <span class="time-text">{{ formatDate(row.created_at) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" align="center" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
              <el-button
                size="small"
                type="primary"
                  text 
                  @click="viewHomework(row)"
                  class="action-btn"
                >
                  <el-icon><View /></el-icon>
                  查看
                </el-button>
                <el-button
                  v-if="authStore.hasAnyRole(['teacher', 'admin'])"
                  size="small"
                  type="warning"
                  text
                @click="editHomework(row)"
                  class="action-btn"
              >
                  <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button
                v-if="authStore.hasAnyRole(['teacher', 'admin'])"
                size="small"
                type="danger"
                  text
                @click="deleteHomework(row)"
                  class="action-btn"
              >
                  <el-icon><Delete /></el-icon>
                删除
              </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div v-if="filteredHomeworks.length === 0 && !loading" class="empty-state">
          <el-empty description="暂无作业数据" :image-size="120">
            <el-button 
              v-if="authStore.hasAnyRole(['teacher', 'admin'])" 
              type="primary" 
              @click="showCreateDialog = true"
            >
              创建第一个作业
            </el-button>
          </el-empty>
        </div>
      </el-card>

      <!-- 创建作业对话框 -->
      <el-dialog
        v-model="showCreateDialog"
        title="创建新作业"
        width="900px"
        class="homework-dialog"
        :close-on-click-modal="false"
      >
        <div class="dialog-header">
          <el-icon size="24" class="dialog-icon"><Plus /></el-icon>
          <span>创建新的课程作业</span>
        </div>
        
        <el-form
          ref="createFormRef"
          :model="newHomework"
          :rules="homeworkRules"
          label-width="100px"
          class="homework-form"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="作业标题" prop="title" required>
            <el-input
                  v-model="newHomework.title" 
                  placeholder="请输入作业标题"
                  size="large"
                  class="form-input"
                >
                  <template #prefix>
                    <el-icon><Collection /></el-icon>
                  </template>
                </el-input>
          </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属课程" prop="course_id" required>
                <el-select 
                  v-model="newHomework.course_id" 
                  placeholder="请选择课程"
                  size="large"
                  class="form-select"
                >
                  <el-option
                    v-for="course in courses"
                    :key="course.id"
                    :label="course.name"
                    :value="course.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="作业描述" prop="description" required>
            <el-input
              v-model="newHomework.description"
              type="textarea"
              :rows="4"
              placeholder="请输入作业描述，包括作业要求、注意事项等"
              class="form-textarea"
            />
          </el-form-item>
          
              <el-form-item label="截止时间" prop="deadline">
                <el-date-picker
                  v-model="newHomework.deadline"
                  type="datetime"
              placeholder="选择截止时间（可选）"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
              size="large"
              class="form-date-picker"
                />
            <div class="form-help">
              <el-icon size="16"><InfoFilled /></el-icon>
              <span>设置作业截止时间，不设置则无时间限制</span>
            </div>
              </el-form-item>

          <el-form-item label="选择题目" prop="problems" required>
            <div class="problem-selection">
              <div class="selection-header">
                <h4>题目选择</h4>
                <p class="selection-help">选择要包含在此作业中的题目，支持多选</p>
                <div class="selection-actions">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="showSmartSelectionDialog = true"
                    class="smart-selection-btn"
                  >
                    <el-icon><Star /></el-icon>
                    🤖 智能选题
                  </el-button>
                  <el-button 
                    type="info" 
                    size="small" 
                    @click="loadAvailableProblems"
                    class="refresh-btn"
                  >
                    <el-icon><Refresh /></el-icon>
                    刷新题目
                  </el-button>
                </div>
              </div>
              <el-table
                :data="availableProblems"
                @selection-change="handleProblemSelection"
                style="width: 100%"
                class="problem-table"
                :header-cell-style="{ background: '#f8f9fa', color: '#606266' }"
                stripe
              >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="title" label="题目标题" min-width="200" />
                <el-table-column prop="type" label="类型" width="100" align="center">
                  <template #default="{ row }">
                    <el-tag :type="getTypeTagType(row.type)" size="small" class="type-tag">
                      {{ getTypeText(row.type) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="points" label="分值" width="80" align="center">
                  <template #default="{ row }">
                    <span class="points-value">{{ row.points }}分</span>
                  </template>
                </el-table-column>
                <el-table-column prop="difficulty" label="难度" width="100" align="center">
                  <template #default="{ row }">
                    <el-tag :type="getDifficultyTagType(row.difficulty)" size="small" class="difficulty-tag">
                      {{ getDifficultyText(row.difficulty) }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
        </el-form>
        
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="showCreateDialog = false" size="large">取消</el-button>
            <el-button 
              type="primary" 
              @click="createHomework" 
              :loading="creating"
              size="large"
              class="submit-btn"
            >
              <el-icon v-if="!creating"><Check /></el-icon>
              {{ creating ? '创建中...' : '创建作业' }}
          </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 智能选题对话框 -->
      <el-dialog
        v-model="showSmartSelectionDialog"
        title="🤖 智能选题助手"
        width="800px"
        class="smart-selection-dialog"
        :close-on-click-modal="false"
      >
        <div class="dialog-header">
          <el-icon size="24" class="dialog-icon"><Star /></el-icon>
          <span>AI智能推荐适合的题目</span>
        </div>
        
        <div class="smart-selection-content">
          <!-- 智能选题配置 -->
          <el-form :model="smartSelectionForm" label-width="120px" class="smart-form">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="题目数量" required>
                  <el-input-number
                    v-model="smartSelectionForm.problemCount"
                    :min="1"
                    :max="20"
                    placeholder="选择题目数量"
                    size="large"
                    class="form-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="难度分布" required>
                  <el-select 
                    v-model="smartSelectionForm.difficultyDistribution" 
                    placeholder="选择难度分布"
                    size="large"
                    class="form-select"
                  >
                    <el-option label="基础为主 (简单:中等:困难 = 4:4:2)" value="basic" />
                    <el-option label="均衡分布 (简单:中等:困难 = 3:4:3)" value="balanced" />
                    <el-option label="挑战为主 (简单:中等:困难 = 2:4:4)" value="challenging" />
                    <el-option label="自定义分布" value="custom" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="题目类型" required>
                  <el-select 
                    v-model="smartSelectionForm.problemTypes" 
                    placeholder="选择题目类型"
                    multiple
                    size="large"
                    class="form-select"
                  >
                    <el-option label="编程题" value="code" />
                    <el-option label="选择题" value="choice" />
                    <el-option label="填空题" value="blank" />
                    <el-option label="简答题" value="short" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="知识点" required>
                  <el-select
                    v-model="smartSelectionForm.knowledgePoints"
                    placeholder="选择相关知识点"
                    size="large"
                    class="form-select"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                  >
                    <el-option label="数组" value="数组" />
                    <el-option label="链表" value="链表" />
                    <el-option label="栈和队列" value="栈和队列" />
                    <el-option label="树和二叉树" value="树和二叉树" />
                    <el-option label="图论" value="图论" />
                    <el-option label="动态规划" value="动态规划" />
                    <el-option label="回溯算法" value="回溯算法" />
                    <el-option label="排序算法" value="排序算法" />
                    <el-option label="查找算法" value="查找算法" />
                    <el-option label="字符串处理" value="字符串处理" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="特殊要求">
              <el-input
                v-model="smartSelectionForm.requirements"
                type="textarea"
                :rows="3"
                placeholder="输入特殊要求，如：必须包含算法题、注重实践等"
                class="form-textarea"
              />
            </el-form-item>
          </el-form>
          
          <!-- 智能推荐结果 -->
          <div v-if="smartRecommendations.length > 0" class="recommendations-section">
            <h4>🎯 AI推荐题目</h4>
            <p class="recommendations-help">根据您的配置，AI为您推荐了以下题目：</p>
            
            <el-table
              :data="smartRecommendations"
              @selection-change="handleSmartRecommendationSelection"
              style="width: 100%"
              class="recommendations-table"
              :header-cell-style="{ background: '#f0f9ff', color: '#0369a1' }"
              stripe
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="title" label="题目标题" min-width="200" />
              <el-table-column prop="type" label="类型" width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="getTypeTagType(row.type)" size="small" class="type-tag">
                    {{ getTypeText(row.type) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="difficulty" label="难度" width="100" align="center">
                <template #default="{ row }">
                  <el-tag :type="getDifficultyTagType(row.difficulty)" size="small" class="difficulty-tag">
                    {{ getDifficultyText(row.difficulty) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="points" label="分值" width="80" align="center">
                <template #default="{ row }">
                  <span class="points-value">{{ row.points }}分</span>
                </template>
              </el-table-column>
              <el-table-column prop="reason" label="推荐理由" min-width="150">
                <template #default="{ row }">
                  <span class="recommendation-reason">{{ row.reason }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="showSmartSelectionDialog = false" size="large">取消</el-button>
            <el-button 
              type="info" 
              @click="generateSmartRecommendations" 
              :loading="smartSelecting"
              size="large"
              class="generate-btn"
            >
              <el-icon v-if="!smartSelecting"><Star /></el-icon>
              {{ smartSelecting ? 'AI分析中...' : '🤖 生成推荐' }}
            </el-button>
            <el-button 
              v-if="smartRecommendations.length > 0"
              type="success" 
              @click="applySmartRecommendations" 
              size="large"
              class="apply-btn"
            >
              <el-icon><Check /></el-icon>
              ✅ 应用推荐
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { homeworksApi, type Homework } from '@/api/homeworks'
import { classesApi } from '@/api/classes'
import { getProblems } from '@/api/problems'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Collection, 
  Plus, 
  Refresh, 
  Filter, 
  Search, 
  Delete, 
  List, 
  Document, 
  Star, 
  Reading, 
  Timer, 
  Calendar, 
  View, 
  Edit, 
  Check, 
  InfoFilled 
} from '@element-plus/icons-vue'
import MainLayout from '@/layouts/MainLayout.vue'

const router = useRouter()
const authStore = useAuthStore()

// 数据
const homeworks = ref<ExtendedHomework[]>([])
const loading = ref(false)
const showCreateDialog = ref(false)
const showSmartSelectionDialog = ref(false)
const creating = ref(false)
const smartSelecting = ref(false)

// 筛选和搜索
const searchQuery = ref('')
const statusFilter = ref('')
const courseFilter = ref('')

// 课程和问题数据
const courses = ref<any[]>([])
const availableProblems = ref<any[]>([])

// 智能选题相关数据
const smartSelectionForm = ref({
  problemCount: 5,
  difficultyDistribution: 'balanced',
  problemTypes: ['code', 'choice'],
  knowledgePoints: [] as string[],
  requirements: ''
})

const smartRecommendations = ref<any[]>([])
const selectedRecommendations = ref<any[]>([])

// 加载课程数据
const loadCourses = async () => {
  try {
    // 先尝试真实的课程API，如果失败则使用班级数据作为fallback
    try {
      const coursesResponse = await fetch('http://localhost:5000/courses', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json'
        }
      })
      if (coursesResponse.ok) {
        const coursesData = await coursesResponse.json()
        courses.value = coursesData.data || []
        console.log('加载课程数据:', courses.value)
        return
      }
    } catch (apiError) {
      console.warn('课程API调用失败，使用班级数据作为替代:', apiError)
    }
    
    // 如果课程API失败，使用班级数据作为替代
    const classes = await classesApi.getClasses()
    courses.value = classes.map(cls => ({
      id: cls.id,
      name: cls.name,
      code: cls.code || 'CLASS',
      description: cls.description || ''
    }))
    console.log('使用班级数据作为课程:', courses.value)
  } catch (error) {
    console.error('加载课程失败:', error)
    // 如果都失败了，提供一个默认课程选项
    courses.value = [{
      id: 1,
      name: '默认课程',
      code: 'DEFAULT',
      description: '系统默认课程'
    }]
  }
}

// 加载可用题目
const loadAvailableProblems = async () => {
  try {
    const response = await getProblems()
    if (response.data && response.data.length > 0) {
      availableProblems.value = response.data
    } else {
      // 如果没有题目数据，使用模拟数据
      availableProblems.value = [
        {
          id: 1,
          title: '两数之和',
          type: 'code',
          difficulty: 'easy',
          points: 20,
          description: '给定一个整数数组 nums 和一个整数目标值 target，请你在该数组中找出和为目标值 target 的那两个整数'
        },
        {
          id: 2,
          title: '选择排序算法',
          type: 'code',
          difficulty: 'medium',
          points: 25,
          description: '实现选择排序算法，对给定的整数数组进行升序排序'
        },
        {
          id: 3,
          title: '二叉树遍历',
          type: 'code',
          difficulty: 'hard',
          points: 30,
          description: '实现二叉树的前序、中序、后序遍历算法'
        },
        {
          id: 4,
          title: '什么是递归？',
          type: 'choice',
          difficulty: 'easy',
          points: 10,
          description: '选择关于递归的正确描述'
        },
        {
          id: 5,
          title: '算法复杂度分析',
          type: 'short',
          difficulty: 'medium',
          points: 15,
          description: '简要说明时间复杂度和空间复杂度的概念'
        }
      ]
    }
  } catch (error) {
    console.error('加载题目失败:', error)
    // 如果API调用失败，使用模拟数据
    availableProblems.value = [
      {
        id: 1,
        title: '两数之和',
        type: 'code',
        difficulty: 'easy',
        points: 20,
        description: '给定一个整数数组 nums 和一个整数目标值 target，请你在该数组中找出和为目标值 target 的那两个整数'
      },
      {
        id: 2,
        title: '选择排序算法',
        type: 'code',
        difficulty: 'medium',
        points: 25,
        description: '实现选择排序算法，对给定的整数数组进行升序排序'
      }
    ]
  }
}

const newHomework = ref({
  title: '',
  description: '',
  course_id: '',
  deadline: '',
  problems: [] as number[]
})

// 扩展Homework接口以包含UI需要的属性
interface ExtendedHomework extends Homework {
  status?: string
  course_id?: number
  course_name?: string
  total_points?: number
  average_score?: number
}

const homeworkRules = {
  title: [
    { required: true, message: '请输入作业标题', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入作业描述', trigger: 'blur' }
  ],
  course_id: [
    { required: true, message: '请选择所属课程', trigger: 'change' }
  ],
  problems: [
    { required: true, message: '请至少选择一道题目', trigger: 'change' }
  ]
}

// 计算属性
const filteredHomeworks = computed(() => {
  return homeworks.value.filter(homework => {
          const matchesSearch = !searchQuery.value || 
        homework.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        (homework.description && homework.description.toLowerCase().includes(searchQuery.value.toLowerCase()))
    
    const matchesStatus = !statusFilter.value || homework.status === statusFilter.value
    const matchesCourse = !courseFilter.value || homework.course_id === parseInt(courseFilter.value)
    
    return matchesSearch && matchesStatus && matchesCourse
  })
})

const activeHomeworksCount = computed(() => {
  return homeworks.value.filter(h => h.status === 'active').length
})

const completedHomeworksCount = computed(() => {
  return homeworks.value.filter(h => h.status === 'ended').length
})

const averageScore = computed(() => {
  const scores = homeworks.value.map(h => h.average_score || 0).filter(s => s > 0)
  if (scores.length === 0) return 0
  return Math.round(scores.reduce((a, b) => a + b, 0) / scores.length)
})

// 工具函数
const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 智能选题辅助函数
const getDifficultyText = (difficulty: string) => {
  const difficultyMap: Record<string, string> = {
    'easy': '简单',
    'medium': '中等',
    'hard': '困难'
  }
  return difficultyMap[difficulty] || difficulty
}

const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'code': '编程题',
    'choice': '选择题',
    'blank': '填空题',
    'short': '简答题'
  }
  return typeMap[type] || type
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: '进行中',
    ended: '已结束',
    pending: '未开始'
  }
  return statusMap[status] || status
}

const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    active: 'success',
    ended: 'info',
    pending: 'warning'
  }
  return typeMap[status] || 'info'
}

const getStatusIcon = (status: string) => {
  const iconMap: Record<string, string> = {
    active: 'Clock',
    ended: 'Check',
    pending: 'Timer'
  }
  return iconMap[status] || 'InfoFilled'
}

const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    code: 'primary',
    choice: 'success',
    blank: 'warning',
    short: 'info'
  }
  return typeMap[type] || 'info'
}

const getDifficultyTagType = (difficulty: string) => {
  const typeMap: Record<string, string> = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return typeMap[difficulty] || 'info'
}

const getDeadlineClass = (deadline: string) => {
  const now = new Date()
  const deadlineDate = new Date(deadline)
  const diffHours = (deadlineDate.getTime() - now.getTime()) / (1000 * 60 * 60)
  
  if (diffHours < 0) return 'deadline-expired'
  if (diffHours < 24) return 'deadline-urgent'
  if (diffHours < 72) return 'deadline-warning'
  return 'deadline-normal'
}

const getRowClassName = ({ row }: { row: ExtendedHomework }) => {
  if (row.status === 'ended') return 'ended-homework-row'
  if (row.status === 'pending') return 'pending-homework-row'
  return ''
}

// 方法
const loadHomeworks = async () => {
  loading.value = true
  try {
    if (authStore.hasAnyRole(['teacher', 'admin'])) {
      homeworks.value = await homeworksApi.getMyHomeworks()
    } else {
      homeworks.value = await homeworksApi.getHomeworks()
    }
  } catch (error) {
    console.error('加载作业失败:', error)
    ElMessage.error('加载作业失败')
  } finally {
    loading.value = false
  }
}

const refreshHomeworks = () => {
  loadHomeworks()
}

const filterHomeworks = () => {
  // 过滤逻辑已在computed中实现
}

const clearFilters = () => {
  searchQuery.value = ''
  statusFilter.value = ''
  courseFilter.value = ''
}

const viewHomework = (homework: Homework) => {
  router.push(`/homeworks/${homework.id}`)
}

const editHomework = (homework: Homework) => {
  ElMessage.info('编辑功能开发中...')
}

const deleteHomework = async (homework: Homework) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除作业"${homework.title}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await homeworksApi.deleteHomework(homework.id)
    ElMessage.success('删除成功')
    loadHomeworks()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除作业失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleProblemSelection = (selection: any[]) => {
  newHomework.value.problems = selection.map(item => item.id)
  console.log('选择的题目:', selection, '题目ID:', newHomework.value.problems)
}

// 智能选题功能
const generateSmartRecommendations = async () => {
  try {
    smartSelecting.value = true
    console.log('开始智能选题:', smartSelectionForm.value)
    
    // 调用模拟推荐算法
    const recommendations = await generateMockRecommendations()
    smartRecommendations.value = recommendations
    
    ElMessage.success(`成功生成 ${recommendations.length} 道推荐题目`)
  } catch (error) {
    console.error('智能选题失败:', error)
    ElMessage.error('智能选题失败，请重试')
  } finally {
    smartSelecting.value = false
  }
}

// 模拟智能推荐算法
const generateMockRecommendations = async (): Promise<any[]> => {
  // 模拟API调用延迟
  await new Promise(resolve => setTimeout(resolve, 2000))
  
  const { problemCount, difficultyDistribution, problemTypes, knowledgePoints } = smartSelectionForm.value
  
  // 从可用题目中筛选和推荐
  const filteredProblems = availableProblems.value.filter(problem => {
    // 按题型筛选
    if (problemTypes.length > 0 && !problemTypes.includes(problem.type)) {
      return false
    }
    
    // 按知识点筛选（简单的关键词匹配）
    if (knowledgePoints.length > 0) {
      const hasKnowledgePoint = knowledgePoints.some(kp => 
        problem.title.toLowerCase().includes(kp.toLowerCase()) ||
        (problem.description && problem.description.toLowerCase().includes(kp.toLowerCase()))
      )
      if (!hasKnowledgePoint) {
        return false
      }
    }
    
    return true
  })
  
  // 按难度分布选择题目
  const recommendations: any[] = []
  let remainingCount = problemCount
  
  // 计算每个难度级别的题目数量
  const difficultyConfig = getDifficultyConfig(difficultyDistribution, problemCount)
  
  for (const [difficulty, count] of Object.entries(difficultyConfig)) {
    if (count > 0 && remainingCount > 0) {
      const difficultyProblems = filteredProblems
        .filter(p => p.difficulty === difficulty)
        .slice(0, Math.min(count, remainingCount))
      
      recommendations.push(...difficultyProblems)
      remainingCount -= difficultyProblems.length
    }
  }
  
  // 如果还有剩余名额，随机补充
  if (remainingCount > 0) {
    const usedIds = new Set(recommendations.map(p => p.id))
    const remainingProblems = filteredProblems.filter(p => !usedIds.has(p.id))
    const additionalProblems = remainingProblems.slice(0, remainingCount)
    recommendations.push(...additionalProblems)
  }
  
  return recommendations.slice(0, problemCount)
}

// 获取难度分布配置
const getDifficultyConfig = (distribution: string, totalCount: number) => {
  const configs: Record<string, Record<string, number>> = {
    basic: { easy: 0.4, medium: 0.4, hard: 0.2 },
    balanced: { easy: 0.3, medium: 0.4, hard: 0.3 },
    challenging: { easy: 0.2, medium: 0.4, hard: 0.4 },
    custom: { easy: 0.33, medium: 0.33, hard: 0.34 }
  }
  
  const config = configs[distribution] || configs.balanced
  
  return {
    easy: Math.floor(totalCount * config.easy),
    medium: Math.floor(totalCount * config.medium),
    hard: Math.floor(totalCount * config.hard)
  }
}

// 处理智能推荐选择
const handleSmartRecommendationSelection = (selection: any[]) => {
  selectedRecommendations.value = selection
  console.log('选择的推荐题目:', selection)
}

// 应用智能推荐
const applySmartRecommendations = () => {
  if (selectedRecommendations.value.length === 0) {
    ElMessage.warning('请先选择要应用的推荐题目')
    return
  }
  
  // 将选中的推荐题目添加到作业中
  const selectedIds = selectedRecommendations.value.map(item => item.id)
  const currentIds = new Set(newHomework.value.problems)
  
  // 合并去重
  const newIds = selectedIds.filter(id => !currentIds.has(id))
  newHomework.value.problems = [...newHomework.value.problems, ...newIds]
  
  ElMessage.success(`已添加 ${newIds.length} 道推荐题目到作业中`)
  
  // 关闭智能选题对话框
  showSmartSelectionDialog.value = false
  
  // 重置选择状态
  selectedRecommendations.value = []
  smartRecommendations.value = []
  
  console.log('应用推荐后的题目列表:', newHomework.value.problems)
}

const createHomework = async () => {
  try {
    creating.value = true
    
    console.log('创建作业数据:', newHomework.value)
    
    // 调用API创建作业
    await homeworksApi.createHomework({
      title: newHomework.value.title,
      description: newHomework.value.description,
      problems: newHomework.value.problems,
      deadline: newHomework.value.deadline,
      course_id: newHomework.value.course_id || undefined  // 如果没有选择课程，传undefined让后端自动处理
    })
    
    ElMessage.success('作业创建成功')
    showCreateDialog.value = false
    newHomework.value = { title: '', description: '', course_id: '', deadline: '', problems: [] as number[] }
    loadHomeworks()
  } catch (error) {
    console.error('创建作业失败:', error)
    ElMessage.error('创建失败')
  } finally {
    creating.value = false
  }
}

onMounted(() => {
  loadHomeworks()
  loadCourses()
  loadAvailableProblems()
})
</script>

<style scoped lang="scss">
.homeworks-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 0;
}

/* 页面头部 */
.page-header {
  position: relative;
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  color: white;
  padding: 40px 30px;
  margin-bottom: 30px;
  overflow: hidden;
}

.header-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
  opacity: 0.3;
}

.header-content {
  position: relative;
  z-index: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1400px;
  margin: 0 auto;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-icon {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  padding: 15px;
  backdrop-filter: blur(10px);
}

.header-text h1 {
  margin: 0 0 8px 0;
  font-size: 32px;
  font-weight: 700;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-text p {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
  max-width: 600px;
  line-height: 1.5;
}

.header-actions {
  display: flex;
  gap: 15px;
}

.action-btn {
  border-radius: 12px;
  padding: 12px 24px;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.primary-btn {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  border: none;
}

.success-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

/* 筛选卡片 */
.filter-card {
  margin: 0 30px 20px;
  max-width: 1400px;
  margin-left: auto;
  margin-right: auto;
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.filter-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-icon {
  color: #409eff;
}

.filter-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.filter-input,
.filter-select {
  width: 100%;
}

.filter-input :deep(.el-input__wrapper),
.filter-select :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.clear-filters-btn {
  border-radius: 20px;
  padding: 8px 16px;
}

/* 统计卡片 */
.stats-section {
  padding: 0 30px 30px;
  max-width: 1400px;
  margin: 0 auto;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
}

.total-icon {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
}

.active-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.completed-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.score-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

/* 作业列表卡片 */
.homeworks-table-card {
  margin: 0 30px 30px;
  max-width: 1400px;
  margin-left: auto;
  margin-right: auto;
  border-radius: 16px;
  border: none;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  color: #409eff;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.refresh-btn {
  border-radius: 20px;
  padding: 8px 16px;
}

/* 表格样式 */
.homeworks-table {
  border-radius: 8px;
  overflow: hidden;
}

.homeworks-table :deep(.el-table__header) {
  background: #f8f9fa;
}

.homeworks-table :deep(.el-table__row:hover) {
  background: #f0f9ff !important;
}

.homework-info {
  padding: 8px 0;
}

.homework-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 12px;
}

.homework-icon {
  width: 40px;
  height: 40px;
  border-radius: 12px;
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  flex-shrink: 0;
}

.homework-details {
  flex: 1;
}

.homework-title {
  margin: 0 0 6px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.homework-description {
  margin: 0;
  color: #606266;
  font-size: 13px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.homework-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.status-tag {
  border-radius: 20px;
  padding: 4px 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.tag-icon {
  margin-right: 2px;
}

.problem-count,
.total-points {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 12px;
}

.course-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.course-icon {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
}

.course-name {
  font-weight: 500;
  color: #303133;
}

.deadline-info {
  display: flex;
  align-items: center;
  gap: 6px;
}

.deadline-icon {
  margin-right: 4px;
}

.deadline-expired {
  color: #f56c6c;
}

.deadline-urgent {
  color: #e6a23c;
}

.deadline-warning {
  color: #f56c6c;
}

.deadline-normal {
  color: #67c23a;
}

.no-deadline {
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 6px;
}

.time-icon {
  color: #909399;
}

.time-text {
  color: #606266;
  font-size: 13px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-btn {
  border-radius: 20px;
  padding: 6px 12px;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 0;
}

/* 特殊行样式 */
:deep(.ended-homework-row) {
  background-color: #f8f9fa !important;
}

:deep(.pending-homework-row) {
  background-color: #fdf6ec !important;
}

/* 对话框样式 */
.homework-dialog {
  border-radius: 16px;
}

.homework-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 20px 24px;
}

.homework-dialog :deep(.el-dialog__body) {
  padding: 24px;
}

.homework-dialog :deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 20px 24px;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.dialog-icon {
  color: #409eff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.submit-btn {
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 600;
}

/* 表单样式 */
.homework-form {
  margin-top: 20px;
}

.form-input :deep(.el-input__wrapper),
.form-select :deep(.el-input__wrapper),
.form-date-picker :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.form-input :deep(.el-input__wrapper):hover,
.form-select :deep(.el-input__wrapper):hover,
.form-date-picker :deep(.el-input__wrapper):hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.form-textarea :deep(.el-textarea__inner) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  resize: vertical;
}

.form-textarea :deep(.el-textarea__inner):hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.form-help {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  color: #909399;
  font-size: 13px;
}

/* 题目选择区域 */
.problem-selection {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px;
  background: #fafafa;
}

.selection-header {
  margin-bottom: 16px;
}

.selection-header h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
}

.selection-help {
  margin: 0;
  color: #909399;
  font-size: 13px;
}

.selection-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.smart-selection-btn {
  border-radius: 20px;
  padding: 8px 16px;
  font-weight: 600;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  border: none;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.smart-selection-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.problem-table {
  border-radius: 8px;
  overflow: hidden;
}

.type-tag,
.difficulty-tag {
  border-radius: 12px;
  padding: 4px 8px;
}

.points-value {
  font-weight: 600;
  color: #409eff;
}

/* 智能选题对话框样式 */
.smart-selection-dialog {
  border-radius: 16px;
}

.smart-selection-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 20px 24px;
}

.smart-selection-dialog :deep(.el-dialog__body) {
  padding: 24px;
}

.smart-selection-dialog :deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 20px 24px;
}

.smart-selection-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.smart-form {
  background: #fafafa;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.smart-form :deep(.el-form-item__label) {
  font-weight: 600;
  color: #303133;
}

.smart-form :deep(.el-input-number__inner),
.smart-form :deep(.el-select__tags) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.smart-form :deep(.el-input-number__inner):hover,
.smart-form :deep(.el-select__tags):hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.smart-form :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.smart-form :deep(.el-input__wrapper):hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.smart-form :deep(.el-textarea__inner) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  resize: vertical;
}

.smart-form :deep(.el-textarea__inner):hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.recommendations-section {
  background: #f0f9ff;
  border: 1px solid #d9ecff;
  border-radius: 8px;
  padding: 16px;
  margin-top: 20px;
}

.recommendations-section h4 {
  margin: 0 0 10px 0;
  color: #0369a1;
  font-size: 16px;
}

.recommendations-help {
  margin: 0 0 15px 0;
  color: #606266;
  font-size: 13px;
}

.recommendations-table {
  border-radius: 8px;
  overflow: hidden;
}

.recommendations-table :deep(.el-table__header) {
  background: #d9ecff;
}

.recommendations-table :deep(.el-table__row:hover) {
  background: #cce6ff !important;
}

.recommendation-reason {
  font-size: 12px;
  color: #909399;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.generate-btn,
.apply-btn {
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 600;
}

.generate-btn {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  border: none;
}

.apply-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-section .el-col {
    margin-bottom: 20px;
  }
}

@media (max-width: 768px) {
  .page-header {
    padding: 30px 20px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  
  .header-text h1 {
    font-size: 24px;
  }
  
  .stats-section,
  .filter-card,
  .homeworks-table-card {
    margin: 0 20px 20px;
  }
  
  .homework-description {
    max-width: 200px;
  }
  
  .homework-meta {
    gap: 8px;
  }
}
</style>

